import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'dart:ui' as ui;

import 'package:flutter/services.dart';

class RightTopTrianglePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        title: Text('右上角三角形'),
      ),
      body: Center(
        child: Stack(
          alignment: Alignment.topRight,
          children: <Widget>[
            Container(
              color: Colors.white,
              width: 300,
              height: 100,
              padding: const EdgeInsets.all(16),
              child: Text('Lorem Ipsum is simply dummy text of the printing and typesetting industry.'),
              foregroundDecoration: const BadgeDecoration(badgeColor: Colors.green,
                  badgeSize: 70, textSpan: TextSpan(text: 'AWESOME',
                      style: TextStyle(color: Colors.white, fontSize: 12))),
            ),
            Padding(
              padding: EdgeInsets.only(right: 10, top: 10),
              child: Image.asset('assets/images/chosen.png', width: 25, height: 25),
            )
          ],
        ),
      ),
    );
  }

}

class BadgeDecoration extends Decoration {
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  const BadgeDecoration({@required this.badgeColor, @required this.badgeSize, @required this.textSpan});

  @override
  BoxPainter createBoxPainter([onChanged]) => _BadgePainter(badgeColor, badgeSize, textSpan);
}

class _BadgePainter extends BoxPainter {
  static const double BASELINE_SHIFT = 1;
  static const double CORNER_RADIUS = 4;
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  _BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    canvas.save();
    canvas.translate(offset.dx + configuration.size.width - badgeSize, offset.dy);
    canvas.drawPath(buildBadgePath(), getBadgePaint());
    // draw text
    final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
//    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
//    textPainter.layout(minWidth: hyp, maxWidth: hyp);
//    final halfHeight = textPainter.size.height / 2;
//    final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) + BASELINE_SHIFT;
//    canvas.translate(v, -v);
    canvas.rotate(0.785398); // 45 degrees
//    textPainter.paint(canvas, Offset.zero);
    final imagePainter = ImagePaint();
    imagePainter.paint(canvas, Size(50, 50));
    canvas.restore();
  }

  Paint getBadgePaint() => Paint()
    ..isAntiAlias = true
    ..color = badgeColor;

  Path buildBadgePath() => Path.combine(
      PathOperation.difference,
      Path()..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize, topRight: Radius.circular(CORNER_RADIUS))),
      Path()
        ..lineTo(0, badgeSize)
        ..lineTo(badgeSize, badgeSize)
        ..close());
}

class ImagePaint extends CustomPainter{
  Paint _paint;
  ui.Image _image;

  ImagePaint() {
    _paint = Paint();
    _loadImage('assets/images/chosen.png').then((res) {
      _image = res;
    });
  }

  /// 加载图片
  Future<ui.Image> _loadImage(String path) async {
    var data = await rootBundle.load(path);
    var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    var info = await codec.getNextFrame();
    return info.image;
  }

  @override
  void paint(Canvas canvas, Size size) {
    if (_image != null) {
      canvas.drawImage(_image, Offset(0, 0), _paint);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
